<template>
  <div class="login-container">
    
    <div class="login-bg"></div>

    
    <el-card shadow="hover" class="login-card">
      <div class="title-box">
        <h2 class="title" >{{title}}</h2>
        <lang-select />
      </div>

      <el-form ref="loginRef" :model="loginForm" :rules="loginRules" class="login-form">
        <!-- 租户选择 -->
        <el-form-item v-if="tenantEnabled" prop="tenantId">
          <el-select
            v-model="loginForm.tenantId"
            filterable
            :placeholder="t('login.selectPlaceholder')"
            style="width: 100%"
            :aria-label="t('login.selectPlaceholder')"
          >
            <el-option
              v-for="item in tenantList"
              :key="item.tenantId"
              :label="item.companyName"
              :value="item.tenantId"
            />
            <template #prefix>
              <svg-icon icon-class="company" class="input-icon" />
            </template>
          </el-select>
        </el-form-item>

        <!-- 用户名 -->
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            type="text"
            size="large"
            auto-complete="off"
            :placeholder="t('login.username')"
          >
            <template #prefix>
              <svg-icon icon-class="user" class="input-icon" />
            </template>
          </el-input>
        </el-form-item>

        <!-- 密码 -->
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            size="large"
            auto-complete="off"
            :placeholder="t('login.password')"
            @keyup.enter="handleLogin"
          >
            <template #prefix>
              <svg-icon icon-class="password" class="input-icon" />
            </template>
          </el-input>
        </el-form-item>

        <!-- 验证码 -->
        <el-form-item v-if="captchaEnabled" prop="code">
          <div class="captcha-row">
            <el-input
              v-model="loginForm.code"
              size="large"
              auto-complete="off"
              :placeholder="t('login.code')"
              @keyup.enter="handleLogin"
            >
              <template #prefix>
                <svg-icon icon-class="validCode" class="input-icon" />
              </template>
            </el-input>
            <img :src="codeUrl" class="login-code-img" :alt="t('login.captchaImage')" @click="getCode" />
          </div>
        </el-form-item>

        <!-- 记住我 -->
        <el-checkbox v-model="loginForm.rememberMe" class="remember">
          {{ t('login.rememberPassword') }}
        </el-checkbox>

        <!-- 登录按钮 -->
        <el-form-item>
          <el-button
            :loading="loading"
            size="large"
            type="primary"
            class="login-btn"
            @click.prevent="handleLogin"
          >
            <span v-if="!loading">{{ t('login.login') }}</span>
            <span v-else>{{ t('login.logging') }}</span>
          </el-button>
        </el-form-item>

        <!-- 注册入口 -->
        <div v-if="register" class="register-link">
          <router-link class="link-type" :to="'/register'">{{ t('login.switchRegisterPage') }}</router-link>
        </div>

        <!-- 社交登录 -->
        <div class="social-login">
          <el-button v-for="btn in socialBtns" :key="btn.type" circle :title="t(btn.title)" @click="doSocialLogin(btn.type)">
            <svg-icon :icon-class="btn.icon" />
          </el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>


<script setup lang="ts">
import { getCodeImg, getTenantList } from '@/api/login';
import { authBinding } from '@/api/system/social/auth';
import { useUserStore } from '@/store/modules/user';
import { LoginData, TenantVO } from '@/api/types';
import { to } from 'await-to-js';
import { HttpStatus } from '@/enums/RespEnum';
import { useI18n } from 'vue-i18n';

//const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const instance = getCurrentInstance();
if (!instance) {
  throw new Error('getCurrentInstance() returned null');
}
const { proxy } = instance;
// 社交登录按钮配置
const socialBtns = ref([
  {
    type: 'github',
    icon: 'github',
    title: 'login.githubLogin'
  },
  {
    type: 'wechat',
    icon: 'wechat',
    title: 'login.wechatLogin'
  }
  // 可根据需要扩展更多第三方登录方式
]);

const title = import.meta.env.VITE_APP_TITLE;
const userStore = useUserStore();
const router = useRouter();
const { t } = useI18n();

const loginForm = ref<LoginData>({
  tenantId: '000000',
  username: 'admin',
  password: 'admin123',
  rememberMe: false,
  code: '',
  uuid: ''
} as LoginData);

const loginRules: ElFormRules = {
  tenantId: [{ required: true, trigger: 'blur', message: t('login.rule.tenantId.required') }],
  username: [{ required: true, trigger: 'blur', message: t('login.rule.username.required') }],
  password: [{ required: true, trigger: 'blur', message: t('login.rule.password.required') }],
  code: [{ required: true, trigger: 'change', message: t('login.rule.code.required') }]
};

const codeUrl = ref('');
const loading = ref(false);
// 验证码开关
const captchaEnabled = ref(true);
// 租户开关
const tenantEnabled = ref(true);

// 注册开关
const register = ref(false);
const redirect = ref('/');
const loginRef = ref<ElFormInstance>();
// 租户列表
const tenantList = ref<TenantVO[]>([]);

watch(
  () => router.currentRoute.value,
  (newRoute: any) => {
    redirect.value = newRoute.query && newRoute.query.redirect && decodeURIComponent(newRoute.query.redirect);
  },
  { immediate: true }
);

const handleLogin = () => {
  loginRef.value?.validate(async (valid: boolean, fields: any) => {
    if (valid) {
      loading.value = true;
      // 勾选了需要记住密码设置在 localStorage 中设置记住用户名和密码
      if (loginForm.value.rememberMe) {
        localStorage.setItem('tenantId', String(loginForm.value.tenantId));
        localStorage.setItem('username', String(loginForm.value.username));
        localStorage.setItem('password', String(loginForm.value.password));
        localStorage.setItem('rememberMe', String(loginForm.value.rememberMe));
      } else {
        // 否则移除
        localStorage.removeItem('tenantId');
        localStorage.removeItem('username');
        localStorage.removeItem('password');
        localStorage.removeItem('rememberMe');
      }
      // 调用action的登录方法
      const [err] = await to(userStore.login(loginForm.value));
      if (!err) {
        const redirectUrl = redirect.value || '/';
        await router.push(redirectUrl);
        loading.value = false;
      } else {
        loading.value = false;
        // 重新获取验证码
        if (captchaEnabled.value) {
          await getCode();
        }
      }
    } else {
      console.log('error submit!', fields);
    }
  });
};

/**
 * 获取验证码
 */
const getCode = async () => {
  const res = await getCodeImg();
   if (!res || !res.data) {
    console.error('获取验证码失败：返回数据为空');
    return;
  }
  const { data } = res;
  captchaEnabled.value = data.captchaEnabled === undefined ? true : data.captchaEnabled;
  if (captchaEnabled.value) {
    codeUrl.value = 'data:image/gif;base64,' + data.img;
    loginForm.value.uuid = data.uuid;
  }
};

const getLoginData = () => {
  const tenantId = localStorage.getItem('tenantId');
  const username = localStorage.getItem('username');
  const password = localStorage.getItem('password');
  const rememberMe = localStorage.getItem('rememberMe');
  loginForm.value = {
    tenantId: tenantId === null ? String(loginForm.value.tenantId) : tenantId,
    username: username === null ? String(loginForm.value.username) : username,
    password: password === null ? String(loginForm.value.password) : String(password),
    rememberMe: rememberMe === null ? false : Boolean(rememberMe)
  } as LoginData;
};

/**
 * 获取租户列表
 */
const initTenantList = async () => {
  try {
    const res = await getTenantList(false);
    
    // 检查响应是否有效
    if (!res || !res.data) {
      console.error('获取租户列表失败：返回数据为空');
      ElMessage.error('获取租户列表失败');
      return;
    }
    
    const { data } = res;
    // 使用默认值确保安全访问属性
    tenantEnabled.value = data.tenantEnabled ?? true;
    
    if (tenantEnabled.value) {
      tenantList.value = data.voList || [];
      if (tenantList.value != null && tenantList.value.length !== 0) {
        loginForm.value.tenantId = tenantList.value[0].tenantId;
      }
    }
  } catch (error) {
    console.error('获取租户列表异常:', error);
    ElMessage.error('获取租户列表失败，请稍后重试');
  }
};

/**
 * 第三方登录
 * @param type
 */
const doSocialLogin = (type: string) => {
  const tenantId = loginForm.value.tenantId;
  if (!tenantId) {
    ElMessage.error(t('login.selectPlaceholder')); // 提示用户选择租户
    return;
  }
  authBinding(type, tenantId).then((res: any) => {
    if (res.code === HttpStatus.SUCCESS) {
      window.location.href = res.data;
    } else {
      ElMessage.error(res.msg);
    }
  });
};

onMounted(() => {
  getCode();
  initTenantList();
  getLoginData();
});
</script>

<style lang="scss" scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  //background: linear-gradient(135deg, #4facfe, #00f2fe);
  background-image:url('@/assets/images/login-background.jpg');
  background-size: cover;
  position: relative;
}

.login-bg {
  position: absolute;
  inset: 0;
 
}

.login-card {
  width: 420px;
  padding: 30px;
  border-radius: 16px;
  z-index: 2;
}

.title-box {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 25px;
  text-align: center;
  .title {
    margin: 0;
    font-weight: bold;
    font-size: 22px;
    color: #333;
    
  }
}

.login-form {
  .el-input {
    height: 44px;
  }
  .input-icon {
    width: 16px;
    color: #909399;
  }
}

.captcha-row {
  display: flex;
  align-items: center;
  gap: 10px;

  .login-code-img {
    height: 44px;
    border-radius: 6px;
    cursor: pointer;
  }
}

.remember {
  margin: 15px 0;
}

.login-btn {
  width: 100%;
  height: 44px;
  font-size: 16px;
  border-radius: 8px;
}

.register-link {
  text-align: right;
  margin-bottom: 10px;
}

.social-login {
  display: flex;
  justify-content: center;
  gap: 12px;
  margin-top: 15px;

  .el-button {
    background: #f5f7fa;
    transition: all 0.2s;
    &:hover {
      background: #409eff;
      color: white;
    }
  }
}
</style>